﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Forms;
using UCL.Data;

namespace DBKit5
{
    public partial class frmDbBackup : Form
    {
        AppDataHelper adh;
        IDatabaseHelper idh;
        public frmDbBackup()
        {
            InitializeComponent();
            ucConnectionBar1.ConnectionChangedHandler += ConnectionChangeEvent;
        }

        private void frmDbBackup_Load(object sender, EventArgs e)
        {
            adh = new AppDataHelper();
            ucConnectionBar1.uc_init();
            MenuItemEventConfig();
        }
        private void ConnectionChangeEvent(IDatabaseHelper objidh)
        {
            this.idh = objidh;
            this.FormLoad_Tables();
        }
        private void FormLoad_Tables()
        {
            if (idh == null) return;
            lbTables.DataSource = idh.SO_GetTables();
        }
        private void MenuItemEventConfig()
        {
            #region 主菜单
            this.cmi取消ToolStripMenuItem.Click += new EventHandler(cmsTableMenuItem_Click);
            this.cmi全选ToolStripMenuItem.Click += new EventHandler(cmsTableMenuItem_Click);
            this.cmi刷新ToolStripMenuItem.Click += new EventHandler(cmsTableMenuItem_Click);
            #endregion
        }

        // mainMenu
        private void cmsTableMenuItem_Click(object s, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)s;
            switch (mi.Name)
            {
                case "cmi全选ToolStripMenuItem":
                    lbTables.SetSelectedAll();
                    break;
                case "cmi取消ToolStripMenuItem":
                    lbTables.SetSelectedAll(false);
                    break;
                case "cmi刷新ToolStripMenuItem":
                    this.FormLoad_Tables();
                    break;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblSummary.Text = string.Format("已选择 {0} 个表，共 {1} 个表", lbTables.SelectedItems.Count, lbTables.Items.Count);
        }

        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            if (tbPath.TextLength == 0) return;
            System.Diagnostics.Process.Start(tbPath.Text);
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog() { SelectedPath = tbPath.Text };
            if (DialogResult.OK != fbd.ShowDialog()) return;
            tbPath.Text = fbd.SelectedPath;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            StringBuilder sberr = new StringBuilder();
            if (lbTables.SelectedItems.Count == 0) sberr.AppendLine("未选择任何表");
            if (tbPath.TextLength == 0) sberr.AppendLine("备份目录未选择");
            if (sberr.Length > 0)
            {
                MessageBox.Show(sberr.ToString());
                return;
            }
            if (!System.IO.Directory.Exists(tbPath.Text))
            {
                if (DialogResult.OK != MessageBox.Show("备份目录不存在，是否创建?")) return;
                System.IO.Directory.CreateDirectory(tbPath.Text);
            }
            MessageBox.Show("备份过程将耗费比较长的时间，请耐心等待程序处理...");

            string[] arrTables = lbTables.GetSelectedValues().ToArray();
            string content, path;

            // 备份数据库
            if (chkToBak.Checked)
            {
                path = string.Format("{0}\\数据库备份.bak", tbPath.Text);
                //idh.Adv_BackupDatabase(path);
            }
            // 导出数据到Excel
            if (chkToExcelData.Checked)
            {
                path = string.Format("{0}\\数据表数据备份.xls", tbPath.Text);
                //idh.Adv_ExportDataToExcel(path, arrTables);
            }

            // 导出通用模型
            if (chkToGMod.Checked)
            {
                path = string.Format("{0}\\数据表通用结构模型{1}.xml", tbPath.Text, DateTime.Now.ToString("yyyyMMddHHmmss"));
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendFormat("<db Name=\"{0}\" Server=\"{1}\" Version=\"{2}\" DbProvider=\"{3}\">{4}", idh.DatabaseName, idh.ServerName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),idh.ProviderName, Environment.NewLine);
                sb.AppendLine(idh.SO_ExportTableStructureAsStandardXmls(arrTables).Values.ToString(Environment.NewLine + Environment.NewLine));
                sb.AppendLine("</db>");
                FileHelper.SaveAsFile(sb.ToString(), path);
            }

            // 导出特性模型
            if (chkToMod.Checked)
            {
                path = string.Format("{0}\\数据表结构模型{1}.xml", tbPath.Text, DateTime.Now.ToString("yyyyMMddHHmmss"));
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.AppendFormat("<db Name=\"{0}\" Server=\"{1}\" Version=\"{2}\" DbProvider=\"{3}\">{4}", idh.DatabaseName, idh.ServerName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), idh.ProviderName, Environment.NewLine);
                sb.AppendLine(idh.SO_ExportTableStructureAsXmls(arrTables).Values.ToString(Environment.NewLine + Environment.NewLine));
                sb.AppendLine("</db>");
                FileHelper.SaveAsFile(sb.ToString(), path);
            }

            // 导出数据到Sql
            if (chkToSqlData.Checked)
            {
                path = string.Format("{0}\\数据表数据备份{1}.sql", tbPath.Text, DateTime.Now.ToString("yyyyMMddHHmmss"));
                content = idh.SO_ExportTableDataAsSqls(arrTables).Values.ToString(Environment.NewLine + Environment.NewLine);
                FileHelper.SaveAsFile(content, path);
            }

            // 导出结构到Sql
            if (chkToSqlSchema.Checked)
            {
                path = string.Format("{0}\\数据表结构备份{1}.sql", tbPath.Text, DateTime.Now.ToString("yyyyMMddHHmmss"));
                content = idh.SO_GetCreateTableStructures(arrTables).Values.ToString(Environment.NewLine + Environment.NewLine);
                FileHelper.SaveAsFile(content, path);
            }
            if (DialogResult.OK != MessageBox.Show("备份成功，是否打开备份目录?", "提示", MessageBoxButtons.OKCancel)) return;
            System.Diagnostics.Process.Start(tbPath.Text);
        }
    }
}
